package com.cv.system.api.user;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cv.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.cv.infra.api.file.FileApi;
import com.cv.system.api.user.dto.UserProfileRespDTO;
import com.cv.system.dal.dataobject.user.SystemUsersDO;
import com.cv.system.dal.mapper.user.SystemUserMapper;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.Optional;

/**
 * 用户 API 接口实现类
 *
 * @author Charles_XDXD
 */
@Service
@DubboService
public class UserApiServiceImpl implements UserApi {

    @Resource
    private SystemUserMapper systemUserMapper;
    
    @DubboReference
    private FileApi fileApi;

    @Override
    public String getNicknameById(Long userId) {
        if (ObjUtil.isEmpty(userId)) {
            return StrUtil.EMPTY;
        }

        return Optional.ofNullable(systemUserMapper.selectById(userId))
                .orElse(new SystemUsersDO().setNickname(StrUtil.EMPTY))
                .getNickname();
    }

    @Override
    public Long getAvatarById(Long userId) {
        if (ObjUtil.isEmpty(userId)) {
            return 0L;
        }

        return Optional.ofNullable(systemUserMapper.selectById(userId))
                .orElse(new SystemUsersDO().setAvatar(0L))
                .getAvatar();
    }
    
    @Override
    public UserProfileRespDTO getProfileById(Long userId) {
        if (ObjUtil.isEmpty(userId)) {
            return new UserProfileRespDTO();
        }
        
        SystemUsersDO systemUsersDO = systemUserMapper.selectById(userId);
        if (ObjUtil.isEmpty(systemUsersDO)) {
            return new UserProfileRespDTO();
        }
        
        return new UserProfileRespDTO()
                .setId(systemUsersDO.getId())
                .setNickname(systemUsersDO.getNickname())
                .setAvatar(systemUsersDO.getAvatar())
                .setAvatarUrl(fileApi.getUrl(systemUsersDO.getAvatar()))
                .setSignature(systemUsersDO.getSignature());
    }

    @Override
    public Integer getActiveUser() {
        LambdaQueryWrapper<SystemUsersDO> wrapper = new LambdaQueryWrapperX<SystemUsersDO>()
                .ge(SystemUsersDO::getLoginDate, LocalDate.now().minusDays(7));
        return Math.toIntExact(systemUserMapper.selectCount(wrapper));
    }

}
